package com.gwlc.common.util;

import com.gwlc.common.core.Tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>lucky-com.gwlc.common.util-TreeTool</p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2021</p>
 * <p>Company: hanchunit@163.com</p>
 *
 * @author hanchun
 * @version 1.0
 * @date 2021/8/16
 */

public class TreeTool {


    public static List<Tree> builderTree() {
        return builderTree(getTrees());
    }

    /**
     * 创建树
     *
     * @param oldTrees 旧的树
     * @return 返回新树
     */
    public static <T extends Tree> List<T> builderTree(List<T> oldTrees) {

        if (oldTrees.isEmpty()) {
            return null;
        }
        List<T> trees = new ArrayList<>(oldTrees);
        Map<Long, T> newTrees = treeToMap(oldTrees);
        // newTrees.addAll(oldTrees);

        for (T tree : trees) {
            for (T oldTree : oldTrees) {
                if (tree.getId().equals(oldTree.getParentId())) {
                    tree.getSubtree().add(oldTree);
                    //  newTrees.remove(oldTree);
                    newTrees.remove(oldTree.getId());
                    System.out.println("删除了id为:" + oldTree.getId());
                }

            }
            System.out.println("新树中还有:" + newTrees);
        }


        return mapToTree(newTrees);
    }

    public static List<Tree> getTrees() {

        List<Tree> trees = new ArrayList<>(64);
        trees.add(new Tree(1L, 0L, "", new ArrayList<>()));
        trees.add(new Tree(2L, 0L, "", new ArrayList<>()));
        trees.add(new Tree(3L, 1L, "", new ArrayList<>()));
        trees.add(new Tree(4L, 3L, "", new ArrayList<>()));
        trees.add(new Tree(5L, 2L, "", new ArrayList<>()));
        trees.add(new Tree(6L, 5L, "", new ArrayList<>()));
        trees.add(new Tree(7L, 6L, "", new ArrayList<>()));
        trees.add(new Tree(8L, 6L, "", new ArrayList<>()));
        trees.add(new Tree(9L, 6L, "", new ArrayList<>()));
        trees.add(new Tree(10L, 6L, "", new ArrayList<>()));
        trees.add(new Tree(11L, 7L, "", new ArrayList<>()));
        trees.add(new Tree(12L, 8L, "", new ArrayList<>()));
        return trees;

    }

    private static <T extends Tree> Map<Long, T> treeToMap(List<T> trees) {
        Map<Long, T> treeMap = new HashMap<>();
        for (T tree : trees) {
            treeMap.put(tree.getId(), tree);
        }
        return treeMap;
    }

    private static <T extends Tree> List<T> mapToTree(Map<Long, T> trees) {
        List<T> treeLists = new ArrayList<>();
        for (Long id : trees.keySet()) {
            treeLists.add(trees.get(id));
        }
        return treeLists;
    }


}
